import { useAccountStore } from '@/config/store/UseAccountStore.ts'
import type { NavigationGuardWithThis, NavigationHookAfter } from 'vue-router'

/**
 * 路由守卫: 设置页面标题
 */
export const SetPageTitleRouterGuard: NavigationHookAfter = (to) => {
    if (!!to.meta.title) {
        document.title = String(to.meta.title)
    }
}

/**
 * 路由守卫: 记录导航日志
 */
export const RouteNavigationLog: NavigationGuardWithThis<any> = (to, from) => {
    console.debug('[路由]', `${ from.path } -> ${ to.path }`)
}

/**
 * 路由前置守卫: 页面鉴权
 */
export const PageAuthentication: NavigationGuardWithThis<any> = (to) => {
    const { isLogin } = useAccountStore()
    if (isLogin) {
        if (to.path === '/login') {
            console.warn('已登录, 不允许访问登录页. 重定向到首页')
            return {
                path: '/',
            }
        }

        return
    }

    if (!to.meta.authorized) {
        return
    }
    console.warn('未登录, 拒绝访问: ', to.fullPath)

    return {
        path: '/login',
    }
}
